/*
 * author: VDaras
 */

#include "Image.h"
#include "SDLException.h"
#include <SDL/SDL_image.h>

namespace sdl
{

/*
 * Constructor opens an image from disk. Throws an exception if an error occurs.
 *
 * @param
 * path: image's location on disk.
 */

Image::Image(const std::string &path)
{
    //open image, if an error occurs..
    if(!Open(path))
    {
        //throw exception using the last error
        throw Exception(SDL_GetError());
    }
}

Image::~Image()
{
}

/*
 * This routine opens an image from the disk and optimizes the buffer's format
 * for the current video display. If an error occurs during loading or optimization
 * the routine returns failure.
 *
 * @param
 * - path: image's location on disk.
 */

bool Image::Open(const std::string& path)
{
    //create a temporary primitive surface and load image
    SDL_Surface *temp = IMG_Load(path.c_str());

    //if loading didn't fail
    if(temp != NULL)
    {
        //create an optimized primitive surface
        SDL_Surface *optimizedSurface = SDL_DisplayFormatAlpha(temp);
        //free temporary unoptimized primitive surface
        SDL_FreeSurface(temp);

        //if optimization didn't fail
        if(optimizedSurface != NULL)
        {
            //set the object's buffer to the temporary surface
            SetBuffer(optimizedSurface);

            //return success
            return true;
        }
    }

    //return failure because an error occured
    return false;
}

};
